const app = getApp();
var server = require('../../utils/server');
var common = require('../../utils/common');
var VideoContext = wx.createVideoContext('video');
var counttime = null;
Page({
  data: {
    event_id: "",
    goodsDetail: "",
    showLoginPop: false,
    showPhonePop: false,
    isCanAdd: true,
    isCanReduce: true,
    isLocate: true,
    scene: '',
    isLogin: false,
    isRegister: false,
    timestap: 0,
    countH: '00',
    countM: '00',
    countS: '00',
    isShowBuyPop: false,
    animationData: [],
    popanimate: [],
    zindex: 1000,
    cart_num: 1,
    param: {},
    isOverDay: false,
    restDay: 0,
    isShowHome: false,
    userParams: {},
    isToBuy: false,
    current: 0,
    showDots: true,
    videourl: '',
    totalCartNum: 0,
    goodsid: "",
    isMakeOrder: false,
    buyType: '' ,//添加数量弹框类型
    isOpen:false,
    channelId:"",//渠道ID
    isDisableLog: false
  },
  onLoad(options = {}) {
    console.log(options)
    if (options.eventid != undefined) {
      this.data.event_id = options.eventid;
      this.data.goodsid = options.goodsid;
    }
    this.data.channelId = options.cid == undefined ? '' : options.cid;
    this.data.scene = options.scene == undefined ? '' : options.scene;
    console.log(getCurrentPages().length)
    if (options.scene != undefined || app.globalData.isFromHome || getCurrentPages().length == 1) {
      app.globalData.refreshTag = true;
      this.setData({
        isShowHome: true
      })
    }
  },
  stopVideo() {
    VideoContext.pause();
    this.setData({
      showDots: true
    })
  },
  showDots() {
    this.setData({
      videourl: this.data.header[this.data.current].videourl
    })
    VideoContext.play();
    this.setData({
      showDots: false
    })
  },
  touchStart(e) {
    console.log(e, 'start')
    this.data.touchx = e.changedTouches[0].clientX;
    this.data.touchy = e.changedTouches[0].clientY;
  },
  touchEnd(e) {
    console.log(e, 'end');
    let endX = e.changedTouches[0].clientX;
    let endY = e.changedTouches[0].clientX;
    console.log(endX - this.data.touchx)
    if (endX - this.data.touchx > 20) { //右滑
      this.setData({
        showDots: true,
        current: parseInt(this.data.current) - 1 >= 0 ? parseInt(this.data.current) - 1 : this.data.header.length - 1
      })
    } else if (endX - this.data.touchx < -20) { //左滑
      this.setData({
        showDots: true,
        current: parseInt(this.data.current) + 1 <= this.data.header.length - 1 ? parseInt(this.data.current) + 1 : 0
      })
    }
    console.log(this.data.current)
  },
  swiperChange(e) {
    console.log(e)
    this.setData({
      current: e.detail.current
    })
  },
  onUnload() {
    console.log('onunload')
    clearTimeout(counttime);
  },
  onHide() {
    clearTimeout(counttime);
  },
  onShow() {
    this.setData({
      timestap: Date.parse(new Date())
    })
    wx.showShareMenu({
      withShareTicket: true
    })
    console.log(app.globalData.isGetWxUserinfo)
    if (app.globalData.isLocate || this.data.isLocate) {
      console.log(12222222)
      this.setData({
        isLocate: app.globalData.isLocate
      })
      this.getDetail();
      this.getUserInfo()
    }
  },
  onPullDownRefresh() {
    this.getDetail();
    this.getUserInfo();
    this.hideBuyPop();
  },
  //解析scene
  decodeScene() {
    server.postJSON(common.storePath + 'voucher/scenedecode/', {
      "scene": this.data.scene
    }, res => {
      var data = res.data;
      if (res.data.errno == '0') {
        console.log(data);
        this.data.event_id = data.data.event_id;
        this.data.goodsid = data.data.goods_id;
        server.postJSON(common.storePath + 'event/goodsdetail/', {
          "event_id": this.data.event_id,
          "goods_id": this.data.goodsid
        }, res => {
          console.log(res.data)
          var res = res.data;
          if (res.errno == "0") {
            wx.hideNavigationBarLoading();
            common.hideLoading();
            this.setData({
              goodsDetail: res.data,
              header: res.data.goods[0].header,
              cart_num: 1
            })
            clearTimeout(counttime);
            if (res.data.event.status == 'going') {
              this.countTime(res.data.event.end_time)
            } else if (res.data.event.status == 'wait') {
              this.countTime(res.data.event.start_time)
            }
            if (res.data.cart_num > 0) {
              this.setData({
                isCanReduce: true
              })
            }
            this.setData({
              isCanAdd: true
            })
          } else{
            common.showErrorToast(res.errmsg)
            setTimeout(function() {
              wx.switchTab({
                url: '../index/index',
              })
            }, 1000)
          }
        })
        if (data.data.channel_id != '') {
          this.data.channelId = data.data.channel_id;
          wx.setStorage({
            key: 'channelid',
            data: data.data.channel_id
          })
        }
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  // 打开定位
  openLocation(e) {
    if (e.detail.errMsg == "openSetting:ok" && e.detail.authSetting['scope.userLocation']) {
      app.globalData.isLocate = true;
      this.setData({
        isLocate: true
      })
      this.getDetail();
    } else {
      this.setData({
        isLocate: false
      })
      common.showErrorToast('需要授权地理位置后使用！');
    }
  },
  getTotalCartNum() {
    server.postJSON(common.storePath + 'eventcart/num', '', res => {
      var res = res.data;
      if (res.errno == "0") {
        this.setData({
          totalCartNum: res.data
        })
      } else {
        common.showErrorToast(res.errmsg)
      }
    })
  },
  goToCart() {
    if (this.data.isLogin || app.globalData.isGetWxUserinfo) {
      app.globalData.cartIndexType=1;
      wx.navigateTo({
        url: '../../pages/cart/cartIndexSec',
      })
    } else {
      this.setData({
        showLoginPop: true
      })
    }
  },
  getDetail() {
    wx.showNavigationBarLoading();
    wx.stopPullDownRefresh();
    clearTimeout(counttime);
    if (this.data.scene != '' && this.data.scene.indexOf('DECODE') > -1) {
      this.decodeScene();
    } else {
      server.postJSON(common.storePath + 'event/goodsdetail/', {
        "event_id": this.data.event_id,
        "goods_id": this.data.goodsid
      }, res => {
        var res = res.data;
        if (res.errno == "0") {
          wx.hideNavigationBarLoading();
          common.hideLoading();
          this.setData({
            goodsDetail: res.data,
            header: res.data.goods[0].header,
            cart_num: 1
          })
          clearTimeout(counttime);
          if (res.data.event.status == 'going') {
            this.countTime(res.data.event.end_time)
          } else if (res.data.event.status == 'wait') {
            this.countTime(res.data.event.start_time)
          }
          if (res.data.quantity_cart > 0) {
            this.setData({
              isCanReduce: true
            })
          }
          this.setData({
            isCanAdd: true
          })
          if (this.data.channelId != '') {
            wx.setStorage({
              key: 'channelid',
              data: this.data.channelId
            })
          }
        } else {
          common.showErrorToast(res.errmsg)
        }
      })
    }

  },
  //手动输入数字
  updateGoodsNum(e) {
    var goodnum = e.detail.value;
    if (goodnum < this.data.goodsDetail.goods[0].quantity) {
      this.setData({
        cart_num: parseInt(goodnum)
      })
    } else {
      this.setData({
        cart_num: parseInt(this.data.goodsDetail.goods[0].quantity)
      })
      common.showErrorToast("库存不足")
    }
  },
  getCurGoodsNum(e) {
    var goodnum = e.detail.value;
    if (goodnum < this.data.goodsDetail.goods[0].quantity) {
      this.setData({
        cart_num: parseInt(goodnum)
      })
    } else {
      this.setData({
        cart_num: parseInt(this.data.goodsDetail.goods[0].quantity)
      })
      common.showErrorToast("库存不足")
    }
  },

  // 添加购物车
  addCart() {
    this.setData({
      isCanAdd: false
    })
    if (this.data.cart_num < this.data.goodsDetail.goods[0].quantity) {
      this.setData({
        cart_num: parseInt(this.data.cart_num) + 1,
        isCanAdd: true
      })
    } else {
      this.setData({
        isCanAdd: true
      })
      common.showErrorToast("库存不足")
    }
  },
  //商品减1
  reduceCart() {
    console.log(this.data.cart_num)
    this.setData({
      isCanReduce: false
    })
    if (this.data.cart_num > 0) {
      this.setData({
        cart_num: parseInt(this.data.cart_num) - 1,
        isCanReduce: true
      })
    } else {
      this.setData({
        isCanReduce: true
      })
    }
  },
  onShareAppMessage(options) {
    console.log('share')
    var detail = this.data.goodsDetail.goods[0];
    if (typeof(detail.retail_price) == "number" && JSON.stringify(detail.retail_price).indexOf('.') > -1) {
      var array = JSON.stringify(detail.retail_price).split('.');
      var newArray = array[0] + '.' + array[1].substring(0, 2)
      detail.retail_price = newArray;
    } else if (typeof(detail.retail_price) == "string" && detail.retail_price.indexOf('.') > -1) {
      var array = detail.retail_price.split('.');
      var newArray = array[0] + '.' + array[1].substring(0, 2)
      detail.retail_price = newArray;
    } else {
      detail.retail_price = parseInt(this.data.goodsDetail.retail_price);
    }
    var img = detail.header[0].url + '-goods_share';
    console.log(img)
    var shareObj = {
      title: ' ￥' + detail.retail_price + ' | ' + detail.name,
      path: '/membership_supply/pages/productDetailM?eventid=' + this.data.goodsDetail.event.event_id + '&&goodsid=' + detail.goods_id + '&&scene=gzh&&cid=' + this.data.channelId,
      imageUrl: img,
      success: function(res) {
        var shareTickets = res.shareTickets == undefined ? '' : res.shareTickets[0];
        if (shareTickets != '') {
          wx.getShareInfo({
            shareTicket: shareTickets,
            success: ret => {
              console.log(ret)
            }
          })
        }
      },
      fail: function() {
        console.log("分享失败")
      }
    }
    console.log(shareObj)
    return shareObj;
  },
  backHome() {
    app.globalData.skipType = 0;
    wx.switchTab({
      url: '../../pages/index/index',
    })
  },
  //获取用户信息
  getUserInfo() {
    wx.login({
      success: resp => {
        wx.getUserInfo({
          success: res => {
            var code = resp.code;
            this.data.userParams = {
              "js_code": code,
              "encryptedData": res.encryptedData,
              "iv": res.iv,
              "userinfo": res.userInfo,
              "longitude": app.globalData.longitude,
              "latitude": app.globalData.latitude,
              "province": app.globalData.locateProvince,
              "city": app.globalData.locateCity
            }
            var that = this;
            server.login(common.basePath + 'miniprogram/login/', that.data.userParams, function(res) {
              if (res.data.errno == "0") {
                app.globalData.sso = res.data.data.sso;
                if (JSON.stringify(res.data.data.member) == "{}") {
                  that.data.isRegister = false;
                } else if ((JSON.stringify(res.data.data.member) != "{}")) {
                  that.data.isRegister = true;
                }
                wx.setStorage({
                  key: "sso",
                  data: res.data.data.sso,
                  success: res => {
                    that.getTotalCartNum();
                    that.setData({
                      isLogin: true
                    })
                    app.globalData.isGetWxUserinfo = true;
                  }
                })
              } else {
                that.data.isLogin=false;
                common.showErrorToast(res.data.errmsg);
              }
            })
          },
          fail: res => {
            this.data.isLogin = false;
          }
        })
      },
      fail: res => {
        this.data.isLogin = false;
      }
    })
  },
  login(e) {
    this.setData({
      isDisableLog: true
    })
    if (e.detail.errMsg == "getUserInfo:ok") {
      wx.login({
        success: resp => {
          wx.getUserInfo({
            success: res => {
              var code = resp.code;
              this.data.userParams = {
                "js_code": code,
                "encryptedData": res.encryptedData,
                "iv": res.iv,
                "userinfo": res.userInfo,
                "longitude": app.globalData.longitude,
                "latitude": app.globalData.latitude,
                "province": app.globalData.locateProvince,
                "city": app.globalData.city
              }
              var that = this;
              server.login(common.basePath + 'miniprogram/login/', this.data.userParams, function(res) {
                if (res.data.errno == "0") {
                  if (JSON.stringify(res.data.data.member) == "{}") {
                    that.data.isRegister = false;
                  } else if ((JSON.stringify(res.data.data.member) != "{}")) {
                    that.data.isRegister = true;
                  }
                  wx.setStorage({
                    key: "sso",
                    data: res.data.data.sso,
                    success: res => {
                      that.getTotalCartNum();
                      that.setData({
                        isLogin: true,
                        showLoginPop: false,
                        isDisableLog: false
                      })
                      app.globalData.isGetWxUserinfo = true
                      common.showErrorToast('登录成功');
                    }
                  })
                } else {
                  that.setData({
                    isDisableLog: false
                  })
                  common.showErrorToast(res.data.errmsg)
                }
              })
            }
          })
        }
      })

    } else {
      this.setData({
        isDisableLog: false
      })
      wx.showToast({
        icon: 'none',
        title: '需要授权用户信息使用元初到家！'
      })
    }
  },
  //本地存储用户信息
  storageUserinfo(data) {
    wx.setStorage({
      key: "userInfo",
      data: data
    })
  },
  hideLoginPop() {
    this.setData({
      showLoginPop: false
    })
  },
  showAgreement() {
    wx.navigateTo({
      url: '../../pages/common/agreement',
    })
  },
  // 倒计时
  countTime(time) {
    //获取当前时间  
    var time = time;
    var date = new Date();
    var now = date.getTime() / 1000;
    //时间差  
    var leftTime = time - now;
    //定义变量 d,h,m,s保存倒计时的时间  
    var d, h, m, s;
    d = Math.floor(leftTime / 60 / 60 / 24);
    if (leftTime > 0) {
      h = d * 24 + Math.floor(leftTime / 60 / 60 % 24);
      m = Math.floor(leftTime / 60 % 60);
      s = Math.floor(leftTime % 60);
    } else if (this.data.goodsDetail.event.status == 'going' && leftTime <= 0) {
      this.getDetail();
    } else if (this.data.goodsDetail.event.status == 'wait' && leftTime <= 0) {
      this.getDetail();
    }
    //将0-9的数字前面加上0，例1变为01
    h = checkTime(h);
    m = checkTime(m);
    s = checkTime(s);

    function checkTime(i) {
      if (i < 10) {
        i = "0" + i;
      }
      return i;
    }
    //将倒计时赋值到div中
    if (d <= 0) {
      this.setData({
        countH: h,
        countM: m,
        countS: s,
        isOverDay: false
      })
    } else {
      this.setData({
        restDay: d,
        isOverDay: true
      })
    }
    var that = this;
    counttime = setTimeout(function() {
      that.countTime(time)
    }, 1000);
  },
  showBuyPop(){
    console.log(2222222222)
    console.log(app.globalData.isGetWxUserinfo, this.data.isLogin)
    if (this.data.isLogin || app.globalData.isGetWxUserinfo) {
      this.setData({
        buyType:0
      })
      var animation = wx.createAnimation({
        duration: 300,
        timingFunction: "ease-in",
        delay: 0
      })
      this.animation = animation;
      animation.translateY(400).step();
      this.setData({
        animationData: animation.export(),
        isShowBuyPop: true
      })
      setTimeout(function() {
        animation.translateY(0).step()
        this.setData({
          animationData: animation.export()
        })
      }.bind(this), 200)
    } else {
      this.setData({
        showLoginPop: true
      })
    }

  },
  hideBuyPop() {
    var animation = wx.createAnimation({
      duration: 300,
      timingFunction: "ease-in",
      delay: 0
    })
    this.animation = animation;
    animation.translateY(400).step();
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function() {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        isShowBuyPop: false
      })
    }.bind(this), 200)
  },
  callServer() {
    wx.makePhoneCall({
      phoneNumber: this.data.goodsDetail.event.service_tel
    })
  },
  addOrder() {
    this.setData({
      isToBuy: true
    })
    server.postJSON(common.storePath + 'eventcart/add', {
      "event_id": this.data.goodsDetail.event.event_id,
      "goods_id": this.data.goodsDetail.goods[0].goods_id,
      "quantity": this.data.cart_num
    }, res => {
      if (res.data.errno == '0') {
        common.showErrorToast('添加成功')
        this.hideBuyPop();
        this.setData({
          isToBuy: false,
          cart_num: 1
        })
        this.getTotalCartNum();
      } else {
        this.setData({
          isToBuy: false
        })
        common.showErrorToast(res.data.errmsg)
      }
    })
  },
  getFormid() {
    server.postJSON(common.basePath + 'miniprogram/getnewtemplateid', {
      "type": "event_book"
    }, res => {
      if (res.data.errno == '0') {
        console.log(res.data.data)
        var ids = [];
        (res.data.data).forEach((item, index) => {
          ids.push(item)
        })
        var that = this;
        console.log(ids)
        if (app.globalData.sdkversion >= 282 && app.globalData.sdkversion != 1997 && app.globalData.sdkversion != 1991) {
          wx.requestSubscribeMessage({
            tmplIds: ids,
            success(res) {
              console.log(res[ids[0]])
              if (res[ids[0]]=='accept'){
                server.postJSON(common.storePath + 'event/book/', {
                  "event_id": that.data.goodsDetail.event.event_id,
                  "form_id": 1
                }, ret => {
                  if (ret.data.errno == '0') {
                    common.showErrorToast("将在活动开始前通过微信通知您")
                  } else {
                    common.showErrorToast(ret.data.errmsg)
                  }
                })
              }else{
                console.log(res)
              }
            },
            fail(res) {
              console.log(res)
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '当前微信版本过低，无法使用订阅消息通知功能，请升级到最新微信版本后重试。',
            success(res) {
              console.log('用户点击确定');
            }
          })
        }
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  goToActivity(e) {
    var voucherEventId = e.currentTarget.dataset.voucherid;
    wx.navigateTo({
      url: '../../activity/pages/activityIndex?scene=' + voucherEventId,
    })
  },
  selectGoods(e) {
    this.data.goodsid = e.currentTarget.dataset.goodsid;
    server.postJSON(common.storePath + 'event/goodsdetail/', {
      "event_id": this.data.event_id,
      "goods_id": e.currentTarget.dataset.goodsid
    }, res => {
      var res = res.data;
      if (res.errno == "0") {
        wx.hideNavigationBarLoading();
        common.hideLoading();
        this.stopVideo();
        wx.pageScrollTo({
          scrollTop: 0,
          duration: 300
        })
        this.setData({
          goodsDetail: res.data,
          header: res.data.goods[0].header,
          cart_num: 1,
          current:0
        })
        this.stopVideo();
        clearTimeout(counttime);
        if (res.data.event.status == 'going') {
          this.countTime(res.data.event.end_time)
        } else if (res.data.event.status == 'wait') {
          this.countTime(res.data.event.start_time)
        }
        if (res.data.quantity_cart > 0) {
          this.setData({
            isCanReduce: true
          })
        }
        this.setData({
          isCanAdd: true
        })
      } else {
        common.showErrorToast(res.errmsg)
      }
    })
  },
  showMakeOrderPop() {
    this.setData({
      buyType: 1
    })
    if (this.data.isLogin || app.globalData.isGetWxUserinfo) {
      var animation = wx.createAnimation({
        duration: 300,
        timingFunction: "ease-in",
        delay: 0
      })
      this.animation = animation;
      animation.translateY(400).step();
      this.setData({
        animationData: animation.export(),
        isShowBuyPop: true
      })
      setTimeout(function() {
        animation.translateY(0).step()
        this.setData({
          animationData: animation.export()
        })
      }.bind(this), 200)
    } else {
      this.setData({
        showLoginPop: true
      })
    }
  },
  makeOrder() {
    console.log(this.data.isRegister)
    if (this.data.isLogin && this.data.isRegister) {
      this.setData({
        isMakeOrder: true
      })
       this.data.param = {
        "address_id": app.globalData.addrId == null ? '' : app.globalData.addrId,
        "event_id": this.data.event_id,
        "coupon_list": [],
        "list": [{
          "goods_id": this.data.goodsid,
          "quantity": this.data.cart_num
        }]
      }
      wx.showLoading({
        title: '结算中...',
      })
      var that = this;
      server.postJSON(common.storePath + 'event/check/', this.data.param, res => {
        if (res.data.errno == '0') {
          wx.hideLoading();
          that.setData({
            isMakeOrder: false,
            isShowBuyPop: false
          })
          res.data.data.event_id = this.data.event_id;
          console.log(res.data.data)
          wx.setStorage({
            key: 'memberaccountlist',
            data: res.data.data,
            success: res => {
              app.globalData.isEditToAccount = false;
              wx.setStorageSync('zgaccountparam', this.data.param);
              wx.navigateTo({
                url: 'accountMember',
              })
            }
          })
        } else {
          that.setData({
            isMakeOrder: false,
            isShowBuyPop: false
          })
          common.showErrorToast(res.data.errmsg)
        }
      })
    } else if (!this.data.isLogin) {
      this.setData({
        showLoginPop: true,
        isShowBuyPop: false
      })
    } else if (!this.data.isRegister) {
      this.setData({
        showPhonePop: true,
        isShowBuyPop: false
      })
    }
  },
  showCheckTel() {
    this.setData({
      showPhonePop: false
    })
    wx.navigateTo({
      url: '../../pages/common/register',
    })
  },
  getPhoneNumber: function(e) {
    var that = this;
    if (e.detail.errMsg != "getPhoneNumber:ok") {
      wx.showToast({
        icon: 'none',
        title: '需要授权手机号后使用元初到家！',
      })
    } else {
      var that = this;
      wx.login({
        success: res => {
          this.setData({
            showPhonePop: false
          });
          server.postJSON(common.basePath + 'miniprogram/registermember/', {
            "iv": e.detail.iv,
            "encryptedData": e.detail.encryptedData,
            "js_code": res.code
          }, res => {
            if (res.data.errno == '0') {
              common.showErrorToast('注册成功');
              that.data.isLogin = true;
              that.data.isRegister = true;
              that.storageUserinfo(res.data.data)
            } else {
              common.showErrorToast(res.data.errmsg);
            }
          })
        }
      })
    }
  },
  goToOpenGroup() {
    this.setData({
      isOpen: true
    })
    console.log(this.data.isOpen)
    server.postJSON(common.basePath + 'voucher/addteam/', {
      "voucher_event_id": this.data.goodsDetail.goods[0].voucher_event_id
    }, res => {
      if (res.data.errno == '0') {
        this.setData({
          isOpen: false
        })
        var data = res.data.data;
        wx.navigateTo({
          url: '../../activity/pages/activity_invite?eventid=' + this.data.goodsDetail.goods[0].voucher_event_id+ '&&teamid=' + data,
        })
      } else {
        this.setData({
          isOpen: false
        })
        common.showErrorToast(res.data.errmsg);
      }
    })

  },
})